package com.qisimanxiang.dalaran.zuul;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.qisimanxiang.dalaran.zuul.sentinel.DegradeStrategy;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class T {


    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), (Runtime.getRuntime().availableProcessors() * 3), 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DefaultThreadFactory("router"), (runnable, ex) -> {
            //TODO 队列满了之后不做处理，实际上链表结构的队列一般不会满的
            System.out.println("Reject");
        });


        try {
            FutureTask task = new FutureTask(() -> {
                Thread.sleep(1000);
                return "success";
            });
            executor.execute(task);
            System.out.println("start");
            long s = System.currentTimeMillis();
            Object o = task.get(2, TimeUnit.SECONDS);
            long e = System.currentTimeMillis();
            System.out.println((e - s) + " result:" + o);

        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.out.println("time out 立即返回");
        }


        Semaphore lock = new Semaphore(2, true);

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                try {
                    long start = System.currentTimeMillis();
                    boolean b = lock.tryAcquire(2, TimeUnit.SECONDS);
                    long end = System.currentTimeMillis();

                    if (b) {
                        System.out.println(System.currentTimeMillis() + ":lock success");
                        Thread.sleep(500);
                        lock.release();
                    } else {
                        System.out.println("lock filed normal " + (end - start));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("lock filed");
                }

            }).start();
        }
    }
}
